package com.zk.tools.util;

import com.sun.mail.imap.IMAPStore;
import com.sun.mail.pop3.POP3Store;
import com.sun.mail.util.MailSSLSocketFactory;
import com.zk.tools.contants.Contants;
import com.zk.tools.model.EmailConfJsonMO;
import com.zk.tools.model.RuleMO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.CollectionUtils;
import javax.mail.Authenticator;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Properties;


public class MailSenderUtil {

    private static final Logger logger = LoggerFactory.getLogger(MailSenderUtil.class);

    public static EmailConfJsonMO emailConfJson;

    public static IMAPStore imapStore;

    public static POP3Store pop3Store;

    public static int mainEmailType;

    public static JavaMailSenderImpl javaMailSender;

    public synchronized static IMAPStore getStoreIMAP() {
        try {
            if (imapStore == null) {
                Session session = javaMailSender.getSession();
                imapStore = (IMAPStore)session.getStore("imap");
            }
            if (!imapStore.isConnected()) {
                String mainEmail = emailConfJson.getMainEmail();
                String pwd = emailConfJson.getMainEmailPwd();
                imapStore.connect("imap.qq.com", Contants.IMAP_PORT_993, mainEmail, pwd);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return imapStore;
    }
    public synchronized static POP3Store getStorePOP3() {
        try {
            if (pop3Store == null) {
                Session session = javaMailSender.getSession();
                pop3Store = (POP3Store)session.getStore("pop3");
            }
            if (!pop3Store.isConnected()) {
                String mainEmail = emailConfJson.getMainEmail();
                String pwd = emailConfJson.getMainEmailPwd();
                pop3Store.connect("pop3.qq.com", Contants.POP3_PORT_995, mainEmail, pwd);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return pop3Store;
    }

    public static void registerJavaMailSenderIMAP(EmailConfJsonMO json) {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        String mainEmail = json.getMainEmail();
        String pwd = json.getMainEmailPwd();
        if (mainEmail.indexOf("@qq.com") != -1) {
            mainEmailType = 0;
            try {
                sender.setProtocol("smtp");
                sender.setHost("smtp.qq.com");
                sender.setPort(Contants.SMTP_PORT_25);
                sender.setUsername(json.getMainEmail());
                sender.setPassword(json.getMainEmailPwd());



                Properties properties = new Properties();
                properties.put("mail.smtp.auth", "true");
                properties.put("mail.smtp.host", "smtp.qq.com");
                properties.setProperty("mail.defaultEncoding", "UTF-8");

                properties.put("mail.transport.protocal", "smtp");
                properties.put("mail.store.protocal", "imap");
                properties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                properties.setProperty("mail.imap.socketFactory.fallback", "false");
                properties.setProperty("mail.imap.port",Contants.IMAP_PORT_993 +"");
                properties.setProperty("mail.imap.socketFactory.port", Contants.IMAP_PORT_993 +"");
                properties.put("mail.transport.class", "com.sun.mail.smtp.SMTPTransport");
                properties.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");


                sender.setJavaMailProperties(properties);
                Authenticator auth =  new MailAuthenticator(json.getMainEmail(), json.getMainEmailPwd());
                Session session = Session.getDefaultInstance(properties, auth);
                session.setDebug(true);
                //获取接收邮件对象
                IMAPStore st = (IMAPStore)session.getStore("imap");
                st.connect("imap.qq.com", Contants.IMAP_PORT_993, mainEmail, pwd);
                if (st.isConnected()) {
                    imapStore = st;
                    logger.info("store.isConnected:{}", true);
                } else {
                    logger.error("连接失败!", new RuntimeException(json.toString()));
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        emailConfJson = json;
        javaMailSender = sender;
    }

    public static void registerJavaMailSenderPOP3(EmailConfJsonMO json) {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        String mainEmail = json.getMainEmail();
        String pwd = json.getMainEmailPwd();
        if (mainEmail.indexOf("@qq.com") != -1) {
            mainEmailType = 0;
            Properties props = new Properties();
            MailSSLSocketFactory sf = null;
            try {
                sender.setProtocol("smtp");
                sender.setUsername(json.getMainEmail());
                sender.setPassword(json.getMainEmailPwd());
                sender.setHost("smtp.qq.com");
                sender.setPort(Contants.SMTP_PORT_25);
                sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                props.put("mail.pop3.ssl.enable", true);
                props.put("mail.pop3.ssl.socketFactory", sf);
                props.setProperty("mail.popStore.protocol", "pop3");
                props.setProperty("mail.pop3.port", Contants.POP3_PORT_995 +"");
                props.setProperty("defaultEncoding", "UTF-8");
                sender.setJavaMailProperties(props);
                Session session = sender.getSession();
                POP3Store st = (POP3Store)session.getStore("pop3");
                session.setDebug(true);


                st.connect("pop.qq.com", Contants.POP3_PORT_995, mainEmail, pwd);
                if (st.isConnected()) {
                    pop3Store = st;
                    logger.info("store.isConnected:{}", true);
                } else {
                    logger.error("连接失败!", new RuntimeException(json.toString()));
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        emailConfJson = json;
        javaMailSender = sender;
    }

    public static void handleSubJect(String subject) {
        List<RuleMO> ruleMOs = emailConfJson.getRules();
        for (RuleMO ruleMO : ruleMOs) {
            String ruleType = ruleMO.getType();
            String containStr = ruleMO.getContain();
            if ("subject".equals(ruleType) && subject.contains(containStr)) {
                logger.info("subject ruleType:{},containStr:{}", ruleType, containStr);
                sendEmail(ruleMO, subject);
            }
        }
    }

    public static void handleContent(String content, String subject) {
        List<RuleMO> ruleMOs = emailConfJson.getRules();
        for (RuleMO ruleMO : ruleMOs) {
            String ruleType = ruleMO.getType();
            String containStr = ruleMO.getContain();
            if ("content".equals(ruleType) && content.contains(containStr)) {
                logger.info("content ruleType:{},containStr:{}", ruleType, containStr);
                sendEmail(ruleMO, subject);
            }
        }
    }

    public synchronized static void sendEmail(RuleMO ruleMO, String alarmInfo) {
        List<String> userEmail = ruleMO.getUserEmail();
        String mainEmail = emailConfJson.getMainEmail();
        String content = ruleMO.getSend();
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            InternetAddress[] ids = getInternetAddress(userEmail);
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mainEmail);
            if (ids == null) {
                logger.error("邮件发送:失败,没有配置收件人!");
            } else {
                helper.setTo(ids);
            }
            helper.setCc(emailConfJson.getBakEmail());
            helper.setSubject("EmailUtil:{" + alarmInfo + "}");
            helper.setText(content, false);
            javaMailSender.send(message);
            logger.info("邮件发送:发送成功");
        } catch (Exception e) {
            logger.error("邮件发送:异常!", e);
        }
    }

    public static InternetAddress[] getInternetAddress(List<String> userEmail) throws AddressException {
        if (CollectionUtils.isEmpty(userEmail)) {
            return null;
        }
        int size = userEmail.size();
        InternetAddress[] internetAddresses = new InternetAddress[size];
        for (int i = 0; i < size; i++) {
            internetAddresses[i] = new InternetAddress(userEmail.get(i));
        }
        return internetAddresses;
    }




}
